package com.qianfeng.smartmeeting.filter;

import com.qianfeng.smartmeeting.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService;

    // 构造器注入
    public JwtAuthenticationFilter(JwtUtil jwtUtil, UserDetailsService userDetailsService) {
        this.jwtUtil = jwtUtil;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

//        String requestURI = request.getRequestURI();
//        // 登录和注册接口直接放行，不解析token
//        if (requestURI.contains("/smartmeeting/login") || requestURI.contains("/smartmeeting/register")) {
//            filterChain.doFilter(request, response);
//            return;
//        }

        // 1. 获取请求头中的token
        String token = request.getHeader("Authorization");
        String username = null;

        // 2. 解析token获取用户名
        if (token != null && !token.isEmpty()) {
            try {
                Map<String, Object> claims = jwtUtil.parseToken(token);
                username = (String) claims.get("username");
            } catch (Exception e) {
                // token无效，直接放行（后续Security会处理未认证请求）
                filterChain.doFilter(request, response);
                return;
            }
        }

        if(username != null && SecurityContextHolder.getContext().getAuthentication() == null){
            //加载用户信息
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

            UsernamePasswordAuthenticationToken authToken =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(authToken);
        }

        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }
}
